/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package consensus

import (
	"github.com/golang/protobuf/proto"
	"hundsun.com/hsl/hschain/common/crypto"
	"hundsun.com/hsl/hschain/protos/common"
)

// ##############BlockEndorsementResponse##############
func (m *BlockEndorsementResponse) clone() *BlockEndorsementResponse {
	return &BlockEndorsementResponse{
		BlockNumber:  m.BlockNumber,
		BlockHash:    m.BlockHash,
		ErrorMessage: m.ErrorMessage,
		Signature:    m.Signature,
	}
}

func (m *BlockEndorsementResponse) marshal() []byte {
	bytes, err := proto.Marshal(m)
	if err != nil {
		panic(err)
	}
	return bytes
}

// Sign 对消息进行签 实现SignableMessage接口
func (m *BlockEndorsementResponse) Sign(keyPair crypto.KeyPair) {
	m.Signature = nil
	sig, err := keyPair.Sign(m.clone().marshal())
	if err != nil {
		panic(err)
	}
	m.Signature = &common.Signature{
		Algorithm: uint32(keyPair.GetSignatureAlgorithm()),
		PublicKey: keyPair.PublicKey().Bytes(),
		Signature: sig,
	}
}

// Verify 验证消息中的签名
func (m *BlockEndorsementResponse) Verify() bool {
	if m.Signature == nil || len(m.Signature.Signature) == 0 || len(m.Signature.PublicKey) == 0 {
		return false
	}

	clonedResp := m.clone()
	clonedResp.Signature = nil
	data := clonedResp.marshal()
	publicKey, err := crypto.ParserPublicKeyWithSignatureAlgorithm(m.Signature.PublicKey, int(m.Signature.Algorithm))
	if err != nil {
		return false
	}
	ok, err := publicKey.Verify(data, m.Signature.Signature)
	if err != nil {
		return false
	}
	return ok
}
